from flask import Blueprint, jsonify, request
from werkzeug.utils import secure_filename
import os
from config import UPLOAD_FOLDER, MAX_FILE_SIZE, allowed_file
from services.recognize import recognize

api_bp = Blueprint('api', __name__)

@api_bp.route('upload', methods=['POST'])
def upload_file():
    if 'image' not in request.files:
        return jsonify({'error': 'No file part in the request'}), 400

    file = request.files.get('image')

    errors = []
    success = False
    filename = ""

    if file and allowed_file(file.filename):
        file.seek(0, 2)
        file_size = file.tell()
        file.seek(0)

        if file_size > MAX_FILE_SIZE:
            errors.append(f'File size exceeds {MAX_FILE_SIZE//1024//1024}MB')
        else:
            filename = secure_filename(file.filename)
            file.save(os.path.join(UPLOAD_FOLDER, filename))
            success = True
    else:
        errors.append(f'Invalid file: {file.filename}')

    if success and len(errors) == 0:
        return jsonify({'message': 'Files successfully uploaded', 'data': filename}), 200
    elif success and len(errors) > 0:
        return jsonify({'message': 'Some files were uploaded', 'errors': errors}), 206
    else:
        return jsonify({'error': 'Failed to upload files', 'errors': errors}), 400

@api_bp.route('recognize', methods=['POST'])
def recognize_image():
    filename = request.get_json()['filename']
    return jsonify(recognize(filename)), 200
    

__all__ = ['api_bp']